package cn.yuhh.controller;

import cn.yuhh.entity.Type;
import cn.yuhh.serviec.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Configuration
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private ITypeService typeService;

    @GetMapping("/types")
    public String types(@PageableDefault(size = 10,sort = {"id"},direction= Sort.Direction.DESC) Pageable pageable,
                       Model model) {
        model.addAttribute("types", typeService.listType(pageable));
        return "admin/types";
    }

    @GetMapping("/types/{id}/edit")
    public String editType(@PathVariable Long id, Model model) {
        model.addAttribute("type", typeService.findById(id));
        return "admin/types-input";
    }

    @GetMapping("/types/{id}/delete")
    public String deleteType(@PathVariable Long id, RedirectAttributes attributes) {
        typeService.deleteById(id);
        attributes.addFlashAttribute("message", "删除成功!");
        return "redirect:/admin/types";
    }

    @GetMapping("/types/input")
    public String inputType(Model model) {
        model.addAttribute("type", new Type());
        return "admin/types-input";
    }

    @PostMapping("/types/{id}")
    public String inputTypes(@PathVariable Long id, Type type, RedirectAttributes attributes) {
        Type type1=typeService.findByName(type.getName());
        if (type1 != null) {
            attributes.addFlashAttribute("message", "已有同名的类别，请重新修改");
        } else {
            typeService.updateTypeById(id, type);
            attributes.addFlashAttribute("message", "修改成功！");
        }
        return "redirect:/admin/types";
    }

    @PostMapping("/types")
    public String inputTypes(@Valid Type type, RedirectAttributes attributes) {
        Type type1=typeService.findByName(type.getName());
        if (type1 != null) {
            attributes.addFlashAttribute("message", "已有同名的类别，请重新修改");
        } else {
            Type t=typeService.save(type);
            if (t != null) {
                attributes.addFlashAttribute("message", "保存成功！");
            } else {
                attributes.addFlashAttribute("message", "保存失败!");
            }
        }
        return "redirect:/admin/types";
    }


}
